﻿using System;
using System.Collections.Generic;

namespace Cngot.Extensions.Logger
{
    public class ErrorMessage
    {
        public ErrorMessage()
        {

        }

        /// <summary>
        /// 异常信息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 堆栈信息
        /// </summary>
        public string StackTrace { get; set; }

        public ErrorMessage InnerError { get; set; }
        public ErrorMessage[] InnerErrors { get; set; }

        public static ErrorMessage Parse(Exception exception)
        {
            if (exception == null)
            {
                return null;
            }

            var error = new ErrorMessage()
            {
                Message = exception.Message,
                StackTrace = exception.StackTrace,
                InnerError = Parse(exception.InnerException)
            };

            List<ErrorMessage> list = new List<ErrorMessage>();
            if (exception is AggregateException aggregateException)
            {
                foreach (var ex in aggregateException.InnerExceptions)
                {
                    list.Add(Parse(ex));
                }
            }
            error.InnerErrors = list.ToArray();

            return error;
        }
    }
}
